﻿using Parylene_CVD.DAL;
using Parylene_CVD.Model;
using Parylene_CVD.Model.DModels;
using Parylene_CVD.Tools;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace Parylene_CVD.ViewModel
{
    /// <summary>
    /// EditUser.xaml 的交互逻辑
    /// </summary>
    public partial class EditUser : Window
    {
        public User EditedUser { get; private set; }
        // 可选职位列表
        public List<string> AvailableRoles { get; } = new List<string>
            {
                GlobalVariables.AdminTitle,
                GlobalVariables.SupervisorTitle,
                GlobalVariables.OperatorTitle
            };

        public EditUser(User user)
        {
            InitializeComponent();
            EditedUser = user;
            DataContext = EditedUser; // 绑定数据上下文
        }

        /// <summary>
        /// 修改用户信息成功保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            // 清空错误信息
            StringBuilder errors = new StringBuilder();

            // 必填项校验
            if (string.IsNullOrWhiteSpace(EditedUser.Username))
            {
                errors.AppendLine("用户名不能为空。");
            }

            if (string.IsNullOrWhiteSpace(EditedUser.Password))
            {
                errors.AppendLine("密码不能为空。");
            }

            if (string.IsNullOrWhiteSpace(EditedUser.Role))
            {
                errors.AppendLine("请选择一个职位。");
            }

            // 长度校验
            if (!string.IsNullOrWhiteSpace(EditedUser.Username) && EditedUser.Username.Length < 3)
            {
                errors.AppendLine("用户名长度必须大于等于3个字符。");
            }

            if (!string.IsNullOrWhiteSpace(EditedUser.Password) && EditedUser.Password.Length < 6)
            {
                errors.AppendLine("密码长度必须大于等于6个字符。");
            }
            // 校验密码中是否包含汉字
            if (!string.IsNullOrWhiteSpace(EditedUser.Password) && EditedUser.Password.Any(c => c >= 0x4e00 && c <= 0x9fa5))  // Unicode 范围内的汉字
            {
                errors.AppendLine("密码不能包含汉字。");
            }
            // 如果有错误，抛出异常或显示提示
            if (errors.Length > 0)
            {
                // 使用异常
                // throw new InvalidOperationException(errors.ToString());

                // 或者显示消息框（需要引用 System.Windows）
                MessageBox.Show(errors.ToString(), "输入错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                DialogResult = false;
            }
            else
            {
                try
                {
                    UserDAL userDAL = new UserDAL();
                    EditedUser.Password = PasswordEncryption.Encrypt(EditedUser.Password);
                    EditedUser.UpdateTime = DateTime.Now;
                    userDAL.UpdataUser(EditedUser, "Username,Password,Role,UpdateTime");
                    DialogResult = true; // 确认保存
                }
                catch (Exception ex)
                {
                    if (ex.Message.Contains("UNIQUE KEY", StringComparison.OrdinalIgnoreCase))
                    {
                        MessageBox.Show("保存失败：用户名重复！", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    else
                    {
                        MessageBox.Show($"保存失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }

                    DialogResult = false; // 保存失败
                }
            }
            
            Close();
        }

        /// <summary>
        /// 点击取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false; // 取消操作
            Close();
        }
    }
}
